<?php
// $Id$

/**
 * User 封装来自 user 数据表的记录及领域逻辑
 */
class User extends QDB_ActiveRecord_Abstract
{

	/**
	 * 返回对象的定义
	 *
	 * @static
	 *
	 * @return array
	 */
	static function __define()
	{
		return array
		(
			// 指定该 ActiveRecord 要使用的行为插件
			'behaviors' => 'acluser',

			// 指定行为插件的配置
			'behaviors_settings' => array
			(
				# '插件名' => array('选项' => 设置),
				'acluser' => array('acl_data_props' => 'name',
								'username_prop' => 'name',
								'password_prop' => 'password',
								'encode_type' => 'md5',
								'update_login_auto' => true,
									'update_login_count_prop' => 'login_count',
									'update_login_at_prop' => 'last_login_time'
								),
			),

			// 用什么数据表保存对象
			'table_name' => 'user',

			// 指定数据表记录字段与对象属性之间的映射关系
			// 没有在此处指定的属性，QeePHP 会自动设置将属性映射为对象的可读写属性
			'props' => array
			(
				// 主键应该是只读，确保领域对象的“不变量”
				'id' => array('readonly' => true),

				/**
				 *  可以在此添加其他属性的设置
				 */
				# 'other_prop' => array('readonly' => true),

				/**
				 * 添加对象间的关联
				 */
				# 'other' => array('has_one' => 'Class'),

			),

			/**
			 * 允许使用 mass-assignment 方式赋值的属性
			 *
			 * 如果指定了 attr_accessible，则忽略 attr_protected 的设置。
			 */
			'attr_accessible' => '',

			/**
			 * 拒绝使用 mass-assignment 方式赋值的属性
			 */
			'attr_protected' => 'id',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值不允许由外部提供
			 *
			 * 这里指定的属性会在创建记录时被过滤掉，从而让数据库自行填充值。
			 */
			'create_reject' => '',

			/**
			 * 指定更新数据库中的对象时，哪些属性的值不允许由外部提供
			 */
			'update_reject' => '',

			/**
			 * 指定在数据库中创建对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 如果填充值为 self::AUTOFILL_TIMESTAMP 或 self::AUTOFILL_DATETIME，
			 * 则会根据属性的类型来自动填充当前时间（整数或字符串）。
			 *
			 * 如果填充值为一个数组，则假定为 callback 方法。
			 */
			'create_autofill' => array
			(
				# 属性名 => 填充值
				# 'is_locked' => 0,
			),

			/**
			 * 指定更新数据库中的对象时，哪些属性的值由下面指定的内容进行覆盖
			 *
			 * 填充值的指定规则同 create_autofill
			 */
			'update_autofill' => array
			(
			),

			/**
			 * 在保存对象时，会按照下面指定的验证规则进行验证。验证失败会抛出异常。
			 *
			 * 除了在保存时自动验证，还可以通过对象的 ::meta()->validate() 方法对数组数据进行验证。
			 *
			 * 如果需要添加一个自定义验证，应该写成
			 *
			 * 'title' => array(
			 *        array(array(__CLASS__, 'checkTitle'), '标题不能为空'),
			 * )
			 *
			 * 然后在该类中添加 checkTitle() 方法。函数原型如下：
			 *
			 * static function checkTitle($title)
			 *
			 * 该方法返回 true 表示通过验证。
			 */
			'validations' => array
			(
			),
		);
	}


/* ------------------ 以下是自动生成的代码，不能修改 ------------------ */

	/**
	 * 开启一个查询，查找符合条件的对象或对象集合
	 *
	 * @static
	 *
	 * @return QDB_Select
	 */
	static function find()
	{
		$args = func_get_args();
		return QDB_ActiveRecord_Meta::instance(__CLASS__)->findByArgs($args);
	}

	/**
	 * 返回当前 ActiveRecord 类的元数据对象
	 *
	 * @static
	 *
	 * @return QDB_ActiveRecord_Meta
	 */
	static function meta()
	{
		return QDB_ActiveRecord_Meta::instance(__CLASS__);
	}


/* ------------------ 以上是自动生成的代码，不能修改 ------------------ */
	
	/**
	 * 用户修改个人密码
	 * @param $old_password 需要验证的旧密码
	 * @param $new_password 保存的新密码
	 * @return 修改成功（失败）
	 */
	static function passwordChange($old_password, $new_password)
	{
		$user = User::find('id=? and password=?', CURRENT_USER_ID, md5($old_password))->getOne();
		if ($user['id'])
		{
			$user->password = $new_password;
			$user->save();
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '用户不存在..');
		}
		
	}

	/**
	 * 管理员重置用户密码
	 * @param $user_id 用户id 
	 * @param $new_password 保存的新密码
	 * @return 重置成功（失败）
	 */
	static function passwordReset($user_id, $new_password)
	{
		$judge = User::judge($user_id);
		if ($judge['ack'] == SUCCESS)
		{
			$user = User::find('id=?', $user_id)->getOne();
			$user->password = $new_password;
			$user->save();
		}
		return array('ack' => $judge['ack'], 'message' => $judge['message']);
	}

	/**
	 * 新建用户
	 * @param $username 用户名
	 * @param $password 密码
	 * @param $department_id 部门id
	 * @param $type 用户权限类型
	 * @return 新建成功(失败)和用户id
	 */
	static function create($username, $password, $type =2)
	{
		$user = User::find('name=?', $username)->asArray()->getOne();
		if ($user['id'])
		{
			return array('ack' => FAILURE, 'message' => 'user is exists!', 'user_id' => $user['id']);
		}
		elseif ($username && $password)
		{
			$user = new user();
			$user->name = $username;
			$user->password = $password;
			$user->type = $type;
			$user->registered_time = CURRENT_DATETIME;
			$user->last_login_time = CURRENT_DATETIME;
			$user->login_count = 0;
			$user->parent_id = CURRENT_USER_ID;
			$user->save();
			return array('ack'=> SUCCESS, 'message' => '', 'user_id' => $user['id']);
		}
		else
		{
			return array('ack' => FAILURE, 'message' => 'username or password is NULL');
		}
	}

	/**
	 * 获取在职状态的用户
	 */
	static function getOnDutyUser()
	{
		return User::find('status=?', Q::ini('custom_flag/user_status/on_duty/value'))->order('name asc')->asArray()->getAll();
	}
	
	/**
	 * 获取超级管理员
	 */
	static function getSuperAdminUser()
	{
		return User::find('type=1')->asArray()->getOne();
	}

	static function search($cp, $ps, $condition)
	{
		$where = self::buildSearchWhere($condition);
		$columns = array(
			'user.*',
		);
		if ($cp == 0 && $ps == 0)
		{
			$select = User::find($where);
			$select->setColumns($columns);
			$pagination = array();
		}
		else
		{
			$select = User::find($where);
			$select->setColumns($columns)->limitPage($cp, $ps);
			$pagination = $select->getPagination();
		}
		$user = $select->asArray()->getAll();
		return array(
				'ack' => SUCCESS,
				'message' => '',
				'data' => $user,
				'pagination' => $pagination
		);
	}
	
	static function buildSearchWhere($condition)
	{
		$where = '1';
		if (! in_array('admin', Q::normalize(CURRENT_USER_ROLES)))
		{
			$where .= ' and user.parent_id=' . CURRENT_USER_ID;			
		}
		if ( ! empty($condition['name']))
		{
			$where .= ' and user.name like \'%' . $condition['name'] . '%\'';
		}
		if ( ! empty($condition['status']))
		{
			$status_filter = '0';
			foreach (Q::ini('custom_flag/user_status') as $us)
			{
				if (isset($condition['status'][$us['value']]) && $condition['status'][$us['value']] == $us['value'])
				{
					$status_filter .= ' or user.status=' . $us['value'];
				}
			}
			$where .= ' and (' . $status_filter . ')';
		}
		return $where;
	}
	
	/**
	 * 离职用户子节点挂载
	 * @param $parent_id 父级id
	 * return array
	 */
	static function cleanMapping($user_id)
	{
		$judge = User::judge($user_id);
		if ($judge['ack'] == SUCCESS)
		{
			$user = User::find('id=?', $user_id)->asArray()->getOne();
			$child = User::find('parent_id=?', $user_id)->getAll();
			foreach ($child as $c)
			{
				$c->parent_id = $user['parent_id'];
				$c->save();
			}
			QDB::getConn()->execute('update user set status=' . Q::ini('custom_flag/user_status/off_duty/value') . ' where id=' . $user_id);
			Roles_Users_Mapping::updateMapping(array(), $user_id);
			Shop_User_Mapping::updateMapping(array(), $user_id);
		}
		return array('ack' => $judge['ack'], 'message' => $judge['message']);
	}
	
	/**
	 * 分配下级管理人员和权限控制
	 */
	static function updateMapping($id, $child_ids) 
	{
		$current_user_child_ids = User::getOffspringById(CURRENT_USER_ID, 'id');
		if (! in_array($id, $current_user_child_ids))
		{
			return array('ack' => FAILURE, 'message' => '当前用户没有权限！请检查是否有下级分配权限');
		}
		else
		{
			$child_old = array();
			$child = User::find('parent_id=?', $id)->asArray()->getAll();
			foreach ($child as $c)
			{
				$child_old[] = $c['id'];
			}
			$child_delete = array_diff($child_old, $child_ids);
			$child_create = array_diff($child_ids, $child_old);
			foreach ($child_delete as $cd)
			{
				$user_delete = User::find('id=?', $cd)->getOne();
				$user_delete->parent_id = CURRENT_USER_ID;
				$user_delete->save();
			}
			foreach ($child_create as $cc)
			{
				$user_create = User::find('id=?', $cc)->getOne();
				$user_create->parent_id = $id;
				$user_create->save();
			}
			Roles_Users_Mapping::updateNextMapping($id);
			return array('ack' => SUCCESS, 'message' => '');
		}
	}
	
	/**
	 * 判断当前用户是否有权限
	 * @param $user_id 用户id
	 * return array
	 */
	static function judge($user_id)
	{
		$user = User::find('id=?', $user_id)->asArray()->getOne();
		if ($user)
		{
			if (! User::isSuperAdmin() && $user['parent_id'] != CURRENT_USER_ID)
			{
				return array('ack' => FAILURE, 'message' => '当前操作人没有权限操作该用户');
			}
			return array('ack' => SUCCESS, 'message' => '');
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '用户不存在');
		}
	}
	
	static function getOffspringById($id, $field='', $level=0)
	{
		$user = User::find('parent_id=? and status=?', $id, Q::ini('custom_flag/user_status/on_duty/value'))->asArray()->getAll();
		if ($user)
		{
			$level++;
			$result = array();
			foreach ($user as $u)
			{
				$u['level'] = $level;
				if ($field)
				{
					$result[] = $u[$field];
				}
				else
				{
					$result[] = $u;
				}
				$ret = User::getOffspringById($u['id'], $field, $level);
				$result = array_merge($result, $ret);
			}
			return $result;
		}
		else
		{
			return array();
		}
	}
	
	/**
	 * 判断是否超级管理员
	 * return true or false
	 */
	static function isSuperAdmin()
	{
		$admin = User::find('type=1')->asArray()->getOne();
		return ($admin['id'] == CURRENT_USER_ID) ? true : false; 
	}
	
	/**
	 * 权限分配绑定
	 * @param int $user_id 分配用户id
	 * @param array $roles_ids 分配角色ids
	 * @param array $shop_ids 分配店铺ids
	 */
	static function bind($user_id, $roles_ids, $shop_ids)
	{
		$judge = User::judgeBind($user_id, $roles_ids, $shop_ids);
		if ($judge['ack'] == SUCCESS)
		{
			Roles_Users_Mapping::updateMapping($roles_ids, $user_id);
			Shop_User_Mapping::updateMapping($shop_ids, $user_id);
			OLM_Permissions::refreshACLFile();
		}
		return array('ack' => $judge['ack'], 'message' => $judge['message']);
	}
	
	/**
	 * 判断权限分配（如是超级管理员可越级分配，否则需判断子级的角色和店铺是否大于父级）
	 * @param 分配用户id $user_id
	 * @param 角色ids $roles_ids
	 * @param 分配店铺ids $shop_ids
	 */
	static function judgeBind($user_id, $roles_ids, $shop_ids)
	{
		$check_in_db = User::find('id=?', $user_id)->asArray()->getOne();
		if ($check_in_db)
		{
			$current_user_child_ids = User::getOffspringById(CURRENT_USER_ID, 'id');
			if (in_array($check_in_db['id'], $current_user_child_ids))
			{
				if (User::isSuperAdmin() && $check_in_db['parent_id'] == CURRENT_USER_ID)
				{
					return array('ack' => SUCCESS, 'message' => '');
				}
				else
				{
					$parent_roles_ids = Roles_Users_Mapping::getUserRolesId($check_in_db['parent_id']);
					$parent_shop_ids = Shop_User_Mapping::getShopIdByUserId($check_in_db['parent_id']);
					if (array_diff($shop_ids, $parent_shop_ids))
					{
						return array('ack' => FAILURE, 'message' => '分配的下级店铺不能大于上级');
					}
					if (array_diff($roles_ids, $parent_roles_ids))
					{
						return array('ack' => FAILURE, 'message' => '分配的下级角色不能大于上级');
					}
					return array('ack' => SUCCESS, 'message' => '');
				}
			}
			else
			{
				return array('ack' => FAILURE, 'message' => '分配用户不属于当前操作人管理范畴，请重新分配！');
			}
		}
		else
		{
			return array('ack' => FAILURE, 'message' => '用户不存在');
		}
	}
	
	 /**
	 * 判断用户数据是否有保存自定义session数据，没有则使用默认session数据
	 * @param 用户name $name
	 */
	static function initCurrentUserCustomSessionData($id)
	{   
		$result = User::find('id=?', $id)->asArray()->getOne();
        if ($result['custom_session_data'])
        {
        	$custom_session_data = json_decode($result['custom_session_data'], true);
        	if (empty($custom_session_data['customize_purchase_stock_analysis']))
        	{
        		$custom_session_data['customize_purchase_stock_analysis'] = array('number' => '产品编号','product_basic_name' => '产品名称','purchase_status' => '采购状态','sales_status' => '销售状态','actual_quantity' => '实际库存','sold_quantity' => '待发数量','warning_quantity' => '警告库存','safe_quantity' => '安全库存','monthly_sales' => '月销','purchase_budget_quantity' => '录单数','purchase_quantity' => '采购数','last_purchase_price' => '最近采购价','oos_days' => '已缺货期');
        	}
        	else if (empty($custom_session_data['customize_sales_stock_analysis']))
        	{
        		$custom_session_data['customize_sales_stock_analysis'] = array('create_time' => '创建时间','number' => '产品编号','product_basic_name' => '产品名称','notes' => '备注','purchase_status' => '采购状态','sales_status' => '销售状态','available_quantity' => '可用库存','sold_quantity' => '待发数量','purchase_quantity' => '采购数','last_purchase_price' => '最近采购价','purchase_price' => '资料成本','weekly_sales' => '周销','monthly_sales' => '月销','purchase_actual_quantity' => '待入库数','warehouse_name' => '所在仓库','weight' => '重量g','oos_days' => '已缺货期');
        	}
        	return $custom_session_data;
        }
        else
        {
        	return array('customize_purchase_stock_analysis' => array('number' => '产品编号','product_basic_name' => '产品名称','purchase_status'=>'采购状态','sales_status'=>'销售状态','actual_quantity'=>'实际库存','sold_quantity'=>'待发数量','warning_quantity'=>'警告库存','safe_quantity'=>'安全库存','monthly_sales'=>'月销','purchase_budget_quantity'=>'录单数','purchase_quantity'=>'采购数','last_purchase_price'=>'最近采购价','oos_days'=>'已缺货期','purchase_note'=>'采购备注'), 'customize_sales_stock_analysis' => array('create_time'=>'创建时间','number'=>'产品编号','product_basic_name'=>'产品名称','notes'=>'备注','purchase_status'=>'采购状态','sales_status'=>'销售状态','available_quantity'=>'可用库存','sold_quantity'=>'待发数量','purchase_quantity'=>'采购数','last_purchase_price'=>'最近采购价','purchase_price'=>'资料成本','weekly_sales'=>'周销','monthly_sales'=>'月销','purchase_actual_quantity'=>'待入库数','warehouse_name'=>'所在仓库','weight'=>'重量g','oos_days'=>'已缺货期')); 
        }
	}
}